package com.molyfun.parents.activity.course.view;

import android.content.Context;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.text.Layout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.R;
import com.molyfun.parents.activity.course.CourseDetailActivity;
import com.molyfun.parents.rest.bean.CourseListResponse;
import com.molyfun.parents.utils.LogUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.carbs.android.expandabletextview.library.ExpandableTextView;

/**
 * Created by william(liuchao.hit@gmail.com).
 * 列表内的展示和外面不用
 * 标题要大写
 */
public class CourseListView extends LinearLayout implements View.OnClickListener, ExpandableTextView.OnExpandListener {

    protected LayoutInflater layoutInflater;
    private String TAG = "CourseView";
    private Context context;
    private boolean inited;

    @InjectView(R.id.course_name)
    TextView mCourseName;
    @InjectView(R.id.topic_complete_state)
    TextView mCompleteState;
//    @InjectView(R.id.tv_looksome)
//    TextView mLooksome;
//
//    @InjectView(R.id.course_performance)
//    TextView mCoursePerformance;
//    @InjectView(R.id.course_feedback)
//    TextView mCourseFeedback;
//    @InjectView(R.id.course_content)
//    TextView mCourseContent;
//    //    @InjectView(R.id.course_expression)
////    TextView mCourseExpression;//课程表现
//    @InjectView(R.id.course_record)
//    TextView mCourseRecord;

    @InjectView(R.id.etv)
    ExpandableTextView etv;
    @InjectView(R.id.attament_state)
    ImageView mAttamentState;
    @InjectView(R.id.line)
    View mLine;

    CourseListResponse.CourseBean mCourseBean;
    FragmentManager mFragmentManager;

    private String mRecordFlag = "";


    public CourseListView(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs);
    }

    public CourseListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CourseListView(Context context) {
        super(context);
        init(context, null);
    }

    //    private boolean mIsOffLine = false;
    private SparseArray<Integer> mPositionsAndStates = new SparseArray<>();
    private int etvWidth;

    private void init(Context context, AttributeSet attrs) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        layoutInflater.inflate(R.layout.widget_list_course, this);
        ButterKnife.inject(this);
    }

    @Override
    public void onExpand(ExpandableTextView view) {
        Object obj = view.getTag();
        if (obj != null && obj instanceof Integer) {
            mPositionsAndStates.put((Integer) obj, view.getExpandState());
        }
        /*if (!TextUtils.isEmpty(mCourseBean.getCourseperformance())) {
//            etv.setText("课堂表现：" + mCourseBean.getCourseperformance());
            mPositionsAndStates.put(0,view.getExpandState());
        } else {
//            etv.setText("暂无课堂表现");
        }*/
    }

    @Override
    public void onShrink(ExpandableTextView view) {
        Object obj = view.getTag();
        if (obj != null && obj instanceof Integer) {
            mPositionsAndStates.put((Integer) obj, view.getExpandState());
        }
        /*if (!TextUtils.isEmpty(mCourseBean.getCourseperformance())) {
//            etv.setText("课堂表现：" + mCourseBean.getCourseperformance());
            mPositionsAndStates.put(0,view.getExpandState());
        } else {
//            etv.setText("暂无课堂表现");
        }*/
    }

    public void initData(CourseListResponse.CourseBean courseBean) {
        initData(courseBean, null);
    }

    public void initData(CourseListResponse.CourseBean courseBean, FragmentManager fragmentManager) {
        initData(courseBean, fragmentManager, false);
    }

    /**
     * init data
     *
     * @param courseBean      courseModel
     * @param fragmentManager used when dialog show
     */
    public void initData(CourseListResponse.CourseBean courseBean, FragmentManager fragmentManager, boolean isLast) {

        if (courseBean == null) {
            return;
        }

        this.mFragmentManager = fragmentManager;
        mCourseBean = courseBean;
        mCourseName.setText(courseBean.getCoursename());

        if(courseBean.getPlanmediaobjectlist() != null && courseBean.getPlanmediaobjectlist().size() > 0){
            mAttamentState.setVisibility(View.VISIBLE);
        }else{
            mAttamentState.setVisibility(View.GONE);
        }

        mRecordFlag = mCourseBean.getSize();

        if (!TextUtils.isEmpty(mCourseBean.getCourseperformance())) {
            etv.setText(mCourseBean.getCourseperformance());
//            etv.setMarqueeRepeatLimit(3);
        } else {
            etv.setText("暂无课堂表现");
        }

//        expand_collapse.setOnClickListener(this);

//        etv.setTag(0);
//        etv.setOnClickListener(this);

        Integer state = mPositionsAndStates.get(0);

//            etv.updateForRecyclerView("课堂表现：" + mCourseBean.getCourseperformance(), etvWidth, state == null ? 0 : state);//第一次getview时肯定为etvWidth为0
        if (!TextUtils.isEmpty(courseBean.getResultname())) {
            mCompleteState.setText("完成情况: " + courseBean.getResultname());
        } else {
            mCompleteState.setText("完成情况: " + "暂无评分");
        }
        mCourseName.setOnClickListener(this);
        mCompleteState.setOnClickListener(this);
        mAttamentState.setOnClickListener(this);

        if(isLast){
            mLine.setVisibility(View.GONE);
        }else{
            mLine.setVisibility(View.VISIBLE);
        }

        setOnClickListener(this);

    }

    public void setOnLongClickListener(OnLongClickListener onLongClickListener) {
        super.setOnLongClickListener(onLongClickListener);
    }


    @Override
    public void onClick(View v) {
//        switch (v.getId()) {

            if (mCourseBean != null) {
                    CourseDetailActivity.startActivity(context, mCourseBean);
                }

//            case R.id.course_performance:
//
//                if (mCourseBean != null) {
//                    CourseDetailActivity.startActivity(context, mCourseBean.getId(), mCourseBean.getCoursename(), mCourseBean.getCoursetarget(), mCourseBean.getCourseprocess());
//                }
//                break;
//
//            case R.id.course_feedback:
//                if (!NetWorkUtil.isNetworkAvailable(context)) {
//                    new CommonEnsureDialogFragment.CommonEnsureDialogBuilder("没有网络，请检查网络")
//                            .build(mFragmentManager.beginTransaction());
//                    return;
//                }
//                if (mCourseBean != null) {
//                    if (mCourseBean.getFeedbacktimes() == 0) {
//                        new CourseFeedbackDialogFragment.CourseFeedbackDialogBuilder(mCourseBean.getId(), mCourseBean.getDkey())
//                                .setCourseFeedbackCallback(new CourseFeedbackDialogFragment.CourseFeedbackCallback() {
//                                    @Override
//                                    public void onFeedbackSuccess() {
//                                    }
//
//                                    @Override
//                                    public void onFeedbackUpdateSuccess(CourseFeedbackEditRequest courseFeedbackEditRequest) {
//
//                                    }
//                                })
//                                .build(mFragmentManager.beginTransaction());
//                    } else {
//                        CourseFeedbackListActivity.startActivity(context, mCourseBean.getId(), Const.CURRENT_COURSE_DAY_STR, mCourseBean);
//                    }
//
//                }
//                break;
//
//            case R.id.course_content:
//                if (mCourseBean != null) {
//                    new CourseContentDialogFragment.CourseContentDialogBuilder(mCourseBean.getCoursename(), mCourseBean.getCoursetarget(), mCourseBean.getCourseprocess())
//                            .build(mFragmentManager.beginTransaction());
//                }
//                break;
//            case R.id.course_record:
//                //课程记录
//                if (mCourseBean != null) {
//                    if (!TextUtils.isEmpty(mRecordFlag) && mRecordFlag.equals("1")) {
//                        CourseRecordActivity.startActivity(context, mCourseBean.getId());
//                    } else {
//                        UIUtils.showToast(MFPApplication.getInstance().getBaseContext(), "无课程记录");
//                    }
//                }
//                break;
//            case R.id.topic_checkbox:
//                if (mCourseBean.isChecked()) {
//                    mCourseBean.setIsChecked(false);
//                } else {
//                    mCourseBean.setIsChecked(true);
//                }
//                if (mCourseViewCallback != null) {
//                    mCourseViewCallback.onCourseCheckChanged(mCourseBean, mCourseBean.isChecked());
//                }
//                break;
//        }
    }


    //    PopupWindow popupWindow;
//    private TextView mDownload;
//
//    private void showPopupWindow(View view) {
//
//        if (mCourseBean == null) {
//            return;
//        }
//        // 一个自定义的布局，作为显示的内容
//        View contentView = LayoutInflater.from(context).inflate(
//                R.layout.view_course_popup_menu, null);
//        mDownload = (TextView) contentView.findViewById(R.id.download);
//        if (TextUtils.isEmpty(mCourseBean.getRelid())) {
//            mDownload.setText("下载");
//        } else {
//            mDownload.setText("已下载");
//        }
//        mDownload.setOnClickListener(this);
//
//        popupWindow = new PopupWindow(contentView,
//                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//        popupWindow.setTouchable(true);
//        popupWindow.setOutsideTouchable(true);
//        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return false;
//            }
//        });
//        popupWindow.showAsDropDown(view);
//
//    }


    private CourseView.CourseViewCallback mCourseViewCallback;

    public void setCourseViewCallback(CourseView.CourseViewCallback courseViewCallback) {
        this.mCourseViewCallback = courseViewCallback;
    }

    public void limitStringTo140(String summerize, final TextView textView, final OnClickListener clickListener) {
        final long startTime = System.currentTimeMillis();
        if (textView == null) return;
        int width = textView.getWidth();//在recyclerView和ListView中，由于复用的原因，这个TextView可能以前就画好了，能获得宽度
        if (width == 0) width = 1000;//获取textview的实际宽度，这里可以用各种方式（一般是dp转px写死）填入TextView的宽度

        int lastCharIndex = getLastCharIndexForLimitTextView(textView, summerize, width, 10);
        if (lastCharIndex < 0 && summerize.length() <= 300) {//如果行数没超过限制
            textView.setText(summerize);
            return;
        }
        //如果超出了行数限制
        textView.setMovementMethod(LinkMovementMethod.getInstance());//this will deprive the recyclerView's focus
        if (lastCharIndex > 300 || lastCharIndex < 0) lastCharIndex = 300;
        String explicitText = null;
        if (summerize.charAt(lastCharIndex) == '\n') {//manual enter
            explicitText = summerize.substring(0, lastCharIndex);
        } else if (lastCharIndex > 12) {//TextView auto enter
            LogUtils.i("Alex", "the last char of this line is --" + lastCharIndex);
            explicitText = summerize.substring(0, lastCharIndex - 12);
        }
        int sourceLength = explicitText.length();
        String showmore = "show more";
        explicitText = explicitText + "..." + showmore;
        final SpannableString mSpan = new SpannableString(explicitText);
        final String finalSummerize = summerize;
        mSpan.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(textView.getResources().getColor(R.color.color_text_setting_desc));
                ds.setAntiAlias(true);
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {//"...show more" click event
                textView.setText(finalSummerize);
                textView.setOnClickListener(null);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (clickListener != null)
                            textView.setOnClickListener(clickListener);//prevent the double click
                    }
                }, 20);
            }
        }, sourceLength, explicitText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(mSpan);
    }

    public static int getLastCharIndexForLimitTextView(TextView textView, String content, int width, int maxLine) {

        TextPaint textPaint = textView.getPaint();
        StaticLayout staticLayout = new StaticLayout(content, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
        if (staticLayout.getLineCount() > maxLine)
            return staticLayout.getLineStart(maxLine) - 1;//exceed
        else return -1;//not exceed the max line
    }
}